package controllers

/*
厦门大学计算机专业 | 前华为工程师
专注《零基础学编程系列》  http://lblbc.cn/blog
包含：Java | 安卓 | 前端 | Flutter | iOS | 小程序 | 鸿蒙
公众号：蓝不蓝编程
*/
import (
	"net/http"
	"strconv"

	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"lblbc.cn/demo/dto"
	"lblbc.cn/demo/helper"
	"lblbc.cn/demo/services"
)

type OrderController interface {
	CreateOrder(ctx *gin.Context)
	QueryOrder(ctx *gin.Context, orderId string)
	QueryByStatus(ctx *gin.Context, status string)
	DeleteOrder(ctx *gin.Context, orderId string)
	getUserIDByToken(token string) string
}

type orderController struct {
	orderService services.OrderService
	jwtService   services.JWTService
}

func NewOrderController(orderService services.OrderService, jwtService services.JWTService) OrderController {
	return &orderController{orderService: orderService, jwtService: jwtService}
}

func (c *orderController) CreateOrder(ctx *gin.Context) {
	var createOrderReq dto.CreateOrderReq
	ctx.ShouldBind(&createOrderReq)
	authHeader := ctx.GetHeader("Authorization")
	userId := c.getUserIDByToken(authHeader)
	userIdInt, _ := strconv.ParseInt(userId, 10, 64)
	result := c.orderService.CreateOrder(userIdInt, createOrderReq.SimpleCartItemList)
	response := helper.SuccessResponse(0, "", result)
	ctx.JSON(http.StatusCreated, response)
}

func (c *orderController) QueryOrder(ctx *gin.Context, orderId string) {
	var result dto.QueryOrderResp = c.orderService.QueryOrder(orderId)
	response := helper.SuccessResponse(0, "", result)
	ctx.JSON(http.StatusOK, response)
}

func (c *orderController) QueryByStatus(ctx *gin.Context, status string) {
	authHeader := ctx.GetHeader("Authorization")
	userId := c.getUserIDByToken(authHeader)
	userIdInt, _ := strconv.ParseInt(userId, 10, 64)

	var result []dto.QueryOrderResp = c.orderService.QueryByStatus(userIdInt, status)
	response := helper.SuccessResponse(0, "", result)
	ctx.JSON(http.StatusOK, response)
}

func (c *orderController) DeleteOrder(ctx *gin.Context, orderId string) {
	c.orderService.DeleteOrder(orderId)
	response := helper.SuccessResponse(0, "", "")
	ctx.JSON(http.StatusOK, response)
}

func (c *orderController) getUserIDByToken(token string) string {
	myToken, err := c.jwtService.ValidateToken(token)
	if err != nil {
		panic(err.Error())
	}
	claims := myToken.Claims.(jwt.MapClaims)
	return claims["user_id"].(string)
}
